package com.example.demo.demos.gui;

import com.example.demo.demos.domain.dto.UploadDTO;
import com.example.demo.demos.service.UploadListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class Page1Panel extends JPanel {

    private JComboBox<String> emailComboBox;
    private JLabel dirLabel, fileLabel;
    private JButton selectDirBtn, selectFileBtn, submitBtn;
    // 统一的组件宽度设置
    private static final int LABEL_WIDTH = 120;    // 标签固定宽度
    private static final int INPUT_WIDTH = 300;    // 输入框固定宽度
    private static final int BUTTON_WIDTH = 100;   // 按钮固定宽度

    // Excel文件扩展名
    private static final String[] EXCEL_EXTENSIONS = {"xls", "xlsx"};
    private static final String EXCEL_DESCRIPTION = "Excel文件 (*.xls, *.xlsx)";

    @Autowired
    private UploadListService uploadListService;

    public Page1Panel() {
        // 设置白色背景
        setBackground(Color.WHITE);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST; // 组件左对齐
        gbc.fill = GridBagConstraints.NONE;   // 不自动填充

        // 邮箱输入
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel emailLabel = new JLabel("邮箱: ");
        setupLabel(emailLabel);
        add(emailLabel, gbc);

        emailComboBox = new JComboBox<>();
        emailComboBox.setEditable(true);
        setupInputComponent(emailComboBox);
        gbc.gridx = 1;
        add(emailComboBox, gbc);

        // 选择目录
        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel dirSelectLabel = new JLabel("选择文件夹: ");
        setupLabel(dirSelectLabel);
        add(dirSelectLabel, gbc);

        dirLabel = new JLabel("未选择");
        dirLabel.setForeground(Color.BLUE);
        setupInputComponent(dirLabel);
        gbc.gridx = 1;
        add(dirLabel, gbc);

        selectDirBtn = new JButton("选择文件夹");
        setupButton(selectDirBtn);
        gbc.gridx = 2;
        add(selectDirBtn, gbc);

        // 选择文件
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel fileSelectLabel = new JLabel("选择Excel文件: ");
        setupLabel(fileSelectLabel);
        add(fileSelectLabel, gbc);

        fileLabel = new JLabel("未选择");
        fileLabel.setForeground(Color.BLUE);
        setupInputComponent(fileLabel);
        gbc.gridx = 1;
        add(fileLabel, gbc);

        selectFileBtn = new JButton("选择文件");
        setupButton(selectFileBtn);
        gbc.gridx = 2;
        add(selectFileBtn, gbc);

        // 提交按钮
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 3;
        gbc.anchor = GridBagConstraints.CENTER;
        submitBtn = new JButton("提交");
        submitBtn.setPreferredSize(new Dimension(150, 30)); // 提交按钮稍大一些
        add(submitBtn, gbc);

        // 初始化事件监听
        initListeners();
    }

    /**
     * 初始化所有按钮的事件监听
     */
    private void initListeners() {
        selectDirBtn.addActionListener(e -> {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                dirLabel.setText(fc.getSelectedFile().getAbsolutePath());
            }
        });

        selectFileBtn.addActionListener(e -> {
            JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    EXCEL_DESCRIPTION, EXCEL_EXTENSIONS);
            fc.setFileFilter(filter);
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

            if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                fileLabel.setText(fc.getSelectedFile().getAbsolutePath());
            }
        });

        submitBtn.addActionListener(e -> {
            // 参数验证
            String email = emailComboBox.getSelectedItem() != null ? emailComboBox.getSelectedItem().toString() : "";
            String dir = dirLabel != null ? dirLabel.getText() : "";
            String filePath = fileLabel != null ? fileLabel.getText() : "";

            if (email.isEmpty() || dir.isEmpty() || filePath.isEmpty() || "未选择".equals(filePath)) {
                JOptionPane.showMessageDialog(this, "请填写所有字段并选择文件！");
                return;
            }

            if (!isValidEmail(email)) {
                JOptionPane.showMessageDialog(this, "请输入有效的邮箱地址！");
                return;
            }

            if (!isExcelFile(filePath)) {
                JOptionPane.showMessageDialog(this, "请选择Excel文件（.xls 或 .xlsx）！",
                        "文件类型错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 更新按钮状态
            submitBtn.setText("正在上传...");
            submitBtn.setEnabled(false);

            // 使用SwingWorker执行耗时操作
            new SwingWorker<UploadDTO, Void>() {
                @Override
                protected UploadDTO doInBackground() throws Exception {
                    return uploadListService.logUpload(email, dir, filePath);
                }

                @Override
                protected void done() {
                    try {
                        UploadDTO up = get();
                        if (up.getStatus().equals(0)) {
                            JOptionPane.showMessageDialog(Page1Panel.this, up.getMsg());
                        } else {
                            JOptionPane.showMessageDialog(Page1Panel.this, "上传成功！");
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(Page1Panel.this, "上传失败：" + ex.getMessage());
                        ex.printStackTrace();
                    } finally {
                        submitBtn.setText("提交");
                        submitBtn.setEnabled(true);
                    }
                }
            }.execute();
        });
    }

    /**
     * 统一设置标签样式
     */
    private void setupLabel(JLabel label) {
        label.setPreferredSize(new Dimension(LABEL_WIDTH, 25));
        label.setHorizontalAlignment(SwingConstants.LEFT); // 左对齐
        label.setBackground(Color.WHITE);
    }

    /**
     * 统一设置输入组件样式
     */
    private void setupInputComponent(JComponent component) {
        component.setPreferredSize(new Dimension(INPUT_WIDTH, 25));
        component.setBackground(Color.WHITE);
    }

    /**
     * 统一设置按钮样式
     */
    private void setupButton(JButton button) {
        button.setPreferredSize(new Dimension(BUTTON_WIDTH, 25));
    }

    /**
     * 加载邮箱历史记录
     */
    public void loadEmailHistory() {
        List<String> history = uploadListService.getMailArr();
        emailComboBox.removeAllItems();
        for (String email : history) {
            emailComboBox.addItem(email);
        }
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }

    /**
     * 验证是否为Excel文件
     */
    private boolean isExcelFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }
        String extension = getFileExtension(filePath);
        for (String ext : EXCEL_EXTENSIONS) {
            if (ext.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filePath) {
        File file = new File(filePath);
        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }
}
